package com.intouchtv.ari;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.widget.ImageView;

public class AnimatedImageView extends ImageView {

    private Bitmap[] images;
    private int currentIndex;

    private long lastUpdateTime;
    private long interval = 100;

    private volatile boolean active;

    public AnimatedImageView(
        Context context,
        Bitmap[] images) {

        super(context);
        this.images = images;
        setImageBitmap(images[0]);
        start();
    }

    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        updateImage();
        if (active) {
            invalidate();
        }
    }

    private void updateImage() {
        long time = System.currentTimeMillis();
        if (time - lastUpdateTime > interval) {
            lastUpdateTime = time;
            currentIndex = (currentIndex + 1) % images.length;
            setImageBitmap(images[currentIndex]);
        }
    }

    public void start() {
        active = true;
    }

    public void stop() {
        active = false;
    }
}
